/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: RoleController.java
 * Author: chen
 * Date: 2024/5/31 12:13
 * Description: 角色controller层
 * History:
 * Date Author Version Desc
 * 2024-01-01 bosssoft 1.0.0 initialize this file
 */
package com.bosssoft.g1.controller;

import com.bosssoft.g1.common.annotation.ApiLog;
import com.bosssoft.g1.common.data.vo.CommonResponse;
import com.bosssoft.g1.common.exception.parse.BusinessException;
import com.bosssoft.g1.dto.*;
import com.bosssoft.g1.group.CreateGroup;
import com.bosssoft.g1.group.UpdateGroup;
import com.bosssoft.g1.utils.CommonResponseUtils;
import com.bosssoft.g1.api.RoleApi;
import com.bosssoft.g1.entity.Node;
import com.bosssoft.g1.query.RoleQuery;
import com.bosssoft.g1.query.UserRoleQuery;
import com.bosssoft.g1.service.RoleService;
import com.bosssoft.g1.vo.CompanyVO;
import com.bosssoft.g1.vo.RoleVO;
import com.bosssoft.g1.vo.UserVO;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: RoleController
 * @description:
 * 解决什么问题：
 * 角色controller层
 * 主要方法：
 * 注意事项：
 * 例如：
 * @author chen
 * @date: 2024/5/31 12:13
 * @since 1.0
 */

@RestController
@RequestMapping("/v1/role")

public class RoleController implements RoleApi {
    /**
     * 角色服务类
     */
    @Autowired
    private RoleService roleService;

    /**
     * 获取所有角色的信息
     *
     * @param pageDTO
     * @return
     */
    @ApiLog
    @GetMapping("/all")
    @Override
    public CommonResponse<PageInfo<RoleVO>> getAllRoles(PageDTO pageDTO) {
        int pageNum = pageDTO.getPageNum();
        int pageSize = pageDTO.getPageSize();

        // 执行查询，获取分页后的角色列表
        PageInfo<RoleDTO> roleDTOPageInfo  = roleService.getAllRoles(pageNum, pageSize);

        // 检查是否获取到了用户信息
        if (roleDTOPageInfo != null) {
            // 将 UserDTO 列表转换为 UserVO 列表
            List<RoleVO> roleVOList = roleDTOPageInfo.getList().stream()
                    .map(this::converterToRoleVO)
                    .collect(Collectors.toList());

        // 创建新的 PageInfo 对象，并设置 RoleVO 列表
        PageInfo<RoleVO> roleVOPageInfo = new PageInfo<>(roleVOList);
        roleVOPageInfo.setPageNum(roleDTOPageInfo.getPageNum());
        roleVOPageInfo.setPageSize(roleDTOPageInfo.getPageSize());
        roleVOPageInfo.setTotal(roleDTOPageInfo.getTotal());
        roleVOPageInfo.setPages(roleDTOPageInfo.getPages());

        // 返回封装的分页结果
        return CommonResponseUtils.success(roleVOPageInfo);
    }else {
            // 查询用户信息失败时返回错误信息
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }

    /**
     * 将roleDTO转换成roleVO
     */
    private RoleVO converterToRoleVO(RoleDTO roleDTO) {
        RoleVO roleVO = new RoleVO();
        roleVO.setId(roleDTO.getId());
        roleVO.setName(roleDTO.getName());
        roleVO.setCode(roleDTO.getCode());
        roleVO.setRemark(roleDTO.getRemark());
        roleVO.setCompanyName(roleDTO.getCompanyName());
        roleVO.setOrganizationName(roleDTO.getOrgName());
        roleVO.setStatus(roleDTO.getStatus());
        roleVO.setCreatedTime(roleDTO.getCreatedTime());
        roleVO.setUpdatedTime(roleDTO.getUpdatedTime());

        return roleVO;
    }

    /**
     * 增加角色
     *
     * @param roleDTO
     * @return CommonResponse
     */
    @ApiLog
    @Override
    public CommonResponse<Boolean> addRole(@NotNull @Validated(CreateGroup.class)  RoleDTO roleDTO) {
        boolean result = roleService.addRole(roleDTO);
        return CommonResponseUtils.booleanResult(result);
    }

    /**
     * 根据角色code进行删除操作
     *
     * @param id
     * @return CommonResponse
     */
    @ApiLog
    @DeleteMapping("/deleteOne")
    @Override
    public CommonResponse<Boolean> deleteRoleById(@NotNull @RequestParam("id") Long id) {
        try {
            Boolean result = roleService.deleteRoleById(id);
            return CommonResponseUtils.booleanResult(result);
        } catch (BusinessException e) {
            return CommonResponseUtils.failedWithMsg("删除失败：", e.getMessage());
        }
    }

    /**
     * 根据RoleDTO进行批量删除操作
     *
     * @param roleDTO
     * @return CommonResponse
     */
    @ApiLog
    @DeleteMapping("/delete")
    @Override
    public CommonResponse<Boolean> batchDeleteRole(@NotEmpty @Valid @RequestBody List<RoleDTO> roleDTO) {
        try {
            Boolean result = roleService.batchDeleteRole(roleDTO);
            return CommonResponseUtils.booleanResult(result);
        } catch (BusinessException e) {
            return CommonResponseUtils.failedWithMsg(String.valueOf(-1), e.getMessage());
        }
    }

    /**
     * 根据角色id进行单个角色信息查询
     *
     * @param id
     * @return CommonResponse
     */
    @ApiLog
    @GetMapping("/query/{id}")
    @Override
    public CommonResponse<RoleDTO> queryRoleById(Long id) {
        RoleDTO roleDTO = roleService.queryRoleById(id);
        if (roleDTO != null) {
            return CommonResponseUtils.success("查询角色信息成功", roleDTO);
        } else {
            return CommonResponseUtils.failed("查询角色信息失败");
        }
    }

    /**
     * 通过角色名查询角色信息
     *
     * @param name
     * @return CommonResponse
     */
    @ApiLog
    @GetMapping("/query")
    @Override
    public CommonResponse<PageInfo<RoleVO>> queryRoles(@RequestParam("pageSize") int pageSize,
                                                       @RequestParam("pageNum") int pageNum,
                                                       @RequestParam(value = "name", required = false) String name) {
        PageInfo<RoleDTO> roleDTOPageInfo =roleService.queryRoles(pageNum,pageSize,name);

        if (roleDTOPageInfo != null) {
            List<RoleVO> roleVOList = roleDTOPageInfo.getList().stream()
                    .map(this::converterToRoleVO)
                    .collect(Collectors.toList());

            PageInfo<RoleVO> roleVOPageInfo = new PageInfo<>(roleVOList);
            roleVOPageInfo.setPageNum(roleDTOPageInfo.getPageNum());
            roleVOPageInfo.setPageSize(roleDTOPageInfo.getPageSize());
            roleVOPageInfo.setTotal(roleDTOPageInfo.getTotal());
            roleVOPageInfo.setPages(roleDTOPageInfo.getPages());
            roleVOPageInfo.setSize(roleDTOPageInfo.getSize());

            return CommonResponseUtils.success(roleVOPageInfo);
        } else {
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }

    /**
     * 通过角色id修改角色信息
     *
     * @param roleDTO
     * @return CommonResponse
     */
    @ApiLog
    @PutMapping("/edit")
    @Override
    public CommonResponse<Boolean> updateRole(@NotNull @Validated(UpdateGroup.class) @RequestBody RoleDTO roleDTO) {
        Boolean result = roleService.updateRole(roleDTO);
        return CommonResponseUtils.booleanResult(result);
    }

    /**
     * 查看权限1——根据角色id查询角色资源树信息
     *
     * @param id
     * @return CommonResponse
     */
    @ApiLog
    @GetMapping("/queryRoleResource")
    @Override
    public CommonResponse<List<Node>> queryRoleResourceByRoId(@RequestParam("id")  Long id) {
        List<Node> nodeList = roleService.queryRoleResourceByRoId(id);
        if (nodeList != null) {
            return CommonResponseUtils.success("通过角色查询资源成功！", nodeList);
        } else {
            return CommonResponseUtils.failed("通过角色查询资源失败");
        }
    }


    /**
     * 查看权限2——根据角色id查询角色所属公司信息
     *
     * @param id
     * @return CommonResponse
     */
    @ApiLog
    @GetMapping("/queryRoleCompany")
    @Override
    public CommonResponse<List<CompanyVO>> queryRoleCompanyByRoId(@RequestParam("id") Long id) {
        List<CompanyDTO> companyDTOS = roleService.queryRoleCompanyByRoId(id);
        List<CompanyVO> companyVOs = companyDTOS.stream().map(dto -> {
            CompanyVO vo = new CompanyVO();
            vo.setId(dto.getId());
            vo.setCode(dto.getCode());
            vo.setName(dto.getName());
            return vo;
        }).collect(Collectors.toList());
        return CommonResponseUtils.success("查询公司信息成功", companyVOs);
    }

    /**
     * 用户分配1 显示用户部分信息
     * @param pageDTO
     * @return CommonResponse
     */
    @ApiLog
    @GetMapping("/queryUser")
    @Override
    public CommonResponse<PageInfo<UserVO>> queryUser(@NotNull @Valid PageDTO pageDTO) {
        PageInfo<UserDTO> userDTOPageInfo = roleService.queryUsers(pageDTO);

        if (userDTOPageInfo != null) {
            List<UserVO> userVOList = userDTOPageInfo.getList().stream()
                    .map(this::convertToUserVO)
                    .collect(Collectors.toList());

            PageInfo<UserVO> userVOPageInfo = new PageInfo<>(userVOList);
            userVOPageInfo.setPageNum(userDTOPageInfo.getPageNum());
            userVOPageInfo.setPageSize(userDTOPageInfo.getPageSize());
            userVOPageInfo.setTotal(userDTOPageInfo.getTotal());
            userVOPageInfo.setPages(userDTOPageInfo.getPages());
            userVOPageInfo.setSize(userDTOPageInfo.getSize());

            return CommonResponseUtils.success(userVOPageInfo);
        } else {
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }

    /**
     * 将userDTO转化为userVO
     * @param userDTO
     * @return
     */
    private UserVO convertToUserVO(UserDTO userDTO) {
        UserVO userVO = new UserVO();
        userVO.setId(userDTO.getId());
        userVO.setCode(userDTO.getCode());
        userVO.setName(userDTO.getName());
        userVO.setCompanyName(userDTO.getCompanyName());
        userVO.setCompanyName(userDTO.getCompanyName());
        userVO.setDepartmentName(userDTO.getDepartmentName());
        userVO.setRoleName(userDTO.getRoleName());
        userVO.setPositionName(userDTO.getPositionName());
        userVO.setSex(userDTO.getSex());
        userVO.setBirthday(userDTO.getBirthday());
        userVO.setTel(userDTO.getTel());
        userVO.setStatus(userDTO.getStatus());
        userVO.setEmail(userDTO.getEmail());

        return userVO;
    }

    /**
     * 角色分配2 进行用户角色分配
     * @param userRoleDTO
     * @return CommonResponse
     */
    @ApiLog
    @PostMapping("/assignUserToRole")
    @Override
    public CommonResponse<Boolean> assignUserToRole(@NotNull @Valid @RequestBody UserRoleDTO userRoleDTO){
        try {
            Boolean result = roleService.assignUserToRole(userRoleDTO);
            return CommonResponseUtils.booleanResult(result);
        } catch (BusinessException e) {
            return CommonResponseUtils.failedWithMsg("用户角色分配失败：",e.getMessage());
        }
    }

    /**
     * 资源分配1——根据用户id查询用户资源树信息
     * @param userRoleQuery
     * @return CommonResponse
     */
    @ApiLog
    @PostMapping("/queryUserResource")
    @Override
    public CommonResponse<List<Node>> queryUserResourceByRole(@NotNull @Valid @RequestBody UserRoleQuery userRoleQuery) {
        List<Node> nodeList = roleService.queryUserResourceByRole(userRoleQuery);
        if (nodeList != null) {
            return CommonResponseUtils.success("通过角色查询资源成功",nodeList);
        } else {
            return CommonResponseUtils.failed("通过角色查询资源失败");
        }
    }

    /**
     * 显示公司信息
     * @return
     */
    @ApiLog
    @Override
    public CommonResponse<List<CompanyVO>> queryCompanys(){
        try {
            List<CompanyDTO> companyDTOs = roleService.getAllCompanies();
            List<CompanyVO> companyVOs = companyDTOs.stream().map(dto -> {
                CompanyVO vo = new CompanyVO();
                vo.setId(dto.getId());
                vo.setCode(dto.getCode());
                vo.setName(dto.getName());
                return vo;
            }).collect(Collectors.toList());
            return CommonResponseUtils.success("查询公司信息成功",companyVOs);
        } catch (BusinessException e) {
            return CommonResponseUtils.failedWithMsg("获取公司信息失败", e.getMessage()) ;
        }
    }

    /**
     * 资源分配3——资源
     *
     * @param roleResourceDTO
     * @return
     */
    @Override
    public CommonResponse<Boolean> assignResourceToRole(@NotNull @Valid @RequestBody RoleResourceDTO roleResourceDTO) {
        try {
            Boolean result = roleService.assignResourceToRole(roleResourceDTO);
            return CommonResponseUtils.booleanResult(result);
        } catch (BusinessException e) {
            return CommonResponseUtils.failedWithMsg(String.valueOf(-1),e.getMessage());
        }

    }

    /**
     * 资源分配4——公司
     *
     * @param roleCompanyDTO
     * @return
     */
    @Override
    public CommonResponse<Boolean> assignCompanyToRole(@NotNull @Valid @RequestBody RoleCompanyDTO roleCompanyDTO) {
        try {
            Boolean result = roleService.assignCompanyToRole(roleCompanyDTO);
            return CommonResponseUtils.booleanResult(result);
        } catch (BusinessException e) {
            return CommonResponseUtils.failedWithMsg(String.valueOf(-1),e.getMessage());
        }

    }
}
